package md

import (
	"log"
	"net"
	"strings"
)

var PublicIP string

func IP() (string, []string) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		log.Println(err)
		return "", []string{}
	}
	var public string
	ipList := make([]string, 0)
	for _, addr := range addrs {
		var ip net.IP
		switch v := addr.(type) {
		case *net.IPNet:
			ip = v.IP
		case *net.IPAddr:
			ip = v.IP
		}
		if ip == nil || ip.IsLoopback() {
			continue
		}
		ip = ip.To4()
		if ip == nil {
			continue
		}
		if isPrivate(ip) {
			ipList = append(ipList, ip.String())
			continue
		}
		public = ip.String()
	}
	if len(ipList) > 0 && public == "" {
		return ipList[0], ipList
	}
	return public, ipList
}

func isPrivate(ip net.IP) bool {
	ipStr := strings.Split(ip.String(), ".")
	if len(ipStr) != 4 {
		return true
	}
	if ipStr[0] == "10" {
		return true
	}
	if ipStr[0] == "172" && (ipStr[1] >= "16" && ipStr[1] <= "31") {
		return true
	}
	if ipStr[0] == "192" && ipStr[1] == "168" {
		return true
	}
	return false
}

func init() {
	PublicIP = strings.Trim(getDefaultIP(), "\r\n")
	if PublicIP == "" {
		PublicIP, _ = IP()
	}
}
